import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {PathAdminService} from './pathAdmin.service';
import {BaseComponent} from '../common/base.component';
import {PathInfo, PathInfoPage} from './pathAdmin';
import {FileUploader} from 'ng2-file-upload';
import {Headers, Http} from '@angular/http';
import {ParamConfig} from '../common/param.config';
import {UserService} from '../user/user.service';
import 'rxjs/add/operator/toPromise';

declare var $: any;

@Component({
  selector: 'app-pathadmin',
  templateUrl: './pathAdmin.component.html'
})
export class PathAdminComponent extends BaseComponent implements OnInit {
  editorTitle: String = '';
  isAddEditor: boolean;
  curPage: Number = 1;
  pathInfoPage: PathInfoPage;
  pathInfo: PathInfo[];
  mapPathInfo: PathInfo[];
  curpathInfo: PathInfo;
  imgUrl: string;
  fileId: string;
  public token: string;
  private hostUrlUpdatePath = ParamConfig.HTTP_WEB_HOST_URL + 'path/updatePath';   // URL to web api
  private hostUrlGetMap = ParamConfig.HTTP_WEB_HOST_URL + 'rbMap/getMapByRobotId'; // 地图MapId
  uploader: FileUploader = new FileUploader({
    url: ParamConfig.HTTP_WEB_HOST_URL + 'rbFile/upload?type=3',
    method: 'POST',
    itemAlias: 'file'
  });

  constructor(private http: Http, private router: Router, private pathAdminService: PathAdminService, private userService: UserService) {
    super();
  }

  ngOnInit() {
    this.curpathInfo = {
      name: '',
      id: '',
      mapId: '',
      status: '',
      fileId: '',
      createTime: ''
    };
    this.searchPath();
  }

  // 文件导入
  selectedFileOnChanged(event: any) {
    console.log(event.target.value);
    // 这里是文件选择完成后的操作处理
    this.uploader.queue[0].onSuccess = (response, status, headers) => {
      // 上传文件成功
      if (status === 200) {
        // 上传文件后获取服务器返回的数据
        const tempRes = JSON.parse(response);
        this.imgUrl = tempRes.systemFileTO.fileUrl;
        this.fileId = tempRes.systemFileTO.fileId;
      } else {
        // 上传文件后获取服务器返回的数据错误
      }
    };
    this.uploader.queue[0].upload(); // 开始上传
  }

  // 查询
  searchPath() {
    this.curPage = 1;
    this.queryList();
  }

  // 新增路径
  onAddPath() {
    this.router.navigate(['/buz/pathAdd']);
  }

  // 修改
  onEditPath(value: PathInfo) {
    this.isAddEditor = false;
    this.editorTitle = '修改路径';
    this.curpathInfo = value;
    this.getMapId();
    $('#data_editor').modal('show'); // 显示编辑对话框
  }

// 新增/修改
  save() {
    if (this.isAddEditor) { // 新增期货数据
    } else { // 修改期货数据
      this.updatePathinfo(this.curpathInfo)
        .then(result => {
            if (result) {
              this.alert.info('修改成功');
              this.queryList();
            } else {
              this.alert.error('修改失败');
            }
          }
        );
    }
    $('#data_editor').modal('hide');
  }

// 删除
  onDeletePath(value: PathInfo) {
    this.curpathInfo = value;
    alert('如果删除该路径，则对应的逻辑基点将被删除');
    $('#delete_confirm').modal('show'); // 显示编辑对话框
  }

// 删除
  delete() {
    this.pathAdminService.removePathinfo(this.curpathInfo)
      .then(result => {
          if (result) {
            this.queryList();
            this.alert.info('删除成功');
          } else {
            this.alert.error('删除失败');
          }
        }
      );
    $('#delete_confirm').modal('hide');
  }

  onPage(event) {
    this.curPage = event;
    this.queryList();
  }

// 查询列表
  private queryList() {
    this.pathAdminService.getPath(this.curPage)
      .then(
        page => {
          this.pathInfoPage = page;
          this.pathInfo = page.pathInfo.datas;
        }
      );
  }

// 修改路径
  updatePathinfo(pathInfo: PathInfo): Promise<any> {
    this.token = this.userService.getToken();
    const request = JSON.stringify({
      id: pathInfo.id,
      name: pathInfo.name,
      status: pathInfo.status,
      mapId: pathInfo.mapId,
      fileId: this.fileId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlUpdatePath, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 查询mapId
  getMapId() {
    this.getMapIdInfo(this.curpathInfo)
      .then(
        res => {
          if (res[0]) {
            this.mapPathInfo = res[1].mapTO;
          }
        }
      );
  }

// 查询MapId
  getMapIdInfo(pathInfo: PathInfo): Promise<any> {
    const request = JSON.stringify({
      robotId: '',
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlGetMap, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          return [true, body];
        }
      )
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<[boolean, any]> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject([false, error.toString()]);
  }
}
